<?php
/**
 * Created by PhpStorm.
 * User: man0sions
 * Date: 16/8/25
 * Time: 下午7:48
 */

namespace src\commands;

use src\base\Spider;
use src\Factory\FormatStrategy\IqiyiFormatStrategy;
use src\Factory\SpiderDataFactory\IqiyiSpiderData;
use src\utils\request\HttpRequest;
use src\utils\request\RandUseragentFetch;

class Iqiyi extends Spider{

    private $rs_video = 4;
    private $site = 2;
    private $spider_data;
    public function __construct()
    {
        $this->spider_data = new IqiyiSpiderData(new IqiyiFormatStrategy());

    }

    public function doSpider($url, $firstcategoryid)
    {
        $request = new HttpRequest($url,new RandUseragentFetch());
        $res = json_decode($request->fetch());
        if($res->status!=200)
        {
            echo "==>fetch error:{$res}\n";
            return false;
        }

        if(count($res->data->videos)==0)
        {
            echo "==>data empty\n";
            return false;
        }

        foreach ($res->data->videos as $key => $val) {
            $this->savePlaylist($val, $firstcategoryid);
        }
    }

    private function savePlaylist($item, $firstcategoryid)
    {
        $item->firstcategoryid = $firstcategoryid;
        $item->creator = 'VideoSpider';
        $item->rs_video =$this->rs_video;
        $item->site =$this->site;
        $playlist = ThirdPlaylist::model()->fields(['*'])
            ->where(['thirdaid' => $item->aid])
            ->find();
        if(!$playlist->getAttributes())
            $playlist = new ThirdPlaylist($new_record=true);
        foreach($this->spider_data->createPlaylistData($item) as $key=>$value)
            $playlist->$key = $value;

        try{
            $playlist->save();
            $count = 0;
            $count = $this->saveVideos($playlist);
            echo "==> 抓取playlist {$playlist->name} : 共 {$count} 集  {$playlist->id} \n";
        }catch(\Exception $e){
            throw new AppException("salve playlist error:{$e}");
        }


    }
}